package binary_search_tree;

public class BinarySearchTree {
    public TreeNode root;

    /**
     * 时间复杂度：
     *      最好情况：O(logN)
     *      最坏情况：O(N)
     * @param key
     * @return
     */
    // 在二叉搜索树中不能插入两个相同的数
    public void insert(int key){
        TreeNode node = new TreeNode(key);
        if(root == null){
            root = node;
            return;
        }
        TreeNode parent = null;
        TreeNode cur = root;
        while(cur != null){
            if(cur.val > key){
                parent = cur;
                cur = cur.left;
            }else if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else{
                return;
            }
        }
        if(key > parent.val){
            parent.right = node;
        }else{
            parent.left = node;
        }
    }

    /**
     * 时间复杂度：
     *      最好情况：O(logN)
     *      最坏情况：O(N)
     * @param key
     * @return
     */
    public TreeNode search(int key){
        TreeNode cur = root;
        while(cur != null){
            if(cur.val > key){
                cur = cur.left;
            } else if (cur.val < key) {
                cur = cur.right;
            }else{
                return cur;
            }
        }
        return null;
    }

    public void remove(int key){
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > key){
                parent = cur;
                cur = cur.left;
            }else{
                removeNode(parent,cur);
                return;
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(parent.left == cur){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(parent.left == cur){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while(target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if(targetParent.left == target){
                targetParent.left = target.right;
            }else{
                targetParent.right = target.right;
            }
        }
    }
}
